﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Rj_GsInsurance.Server.Utils
{
    public class LogHelper
    {
        private static readonly string LogDirectory = Path.Combine(AppContext.BaseDirectory, "Logs");

        static LogHelper()
        {
            // 确保日志文件夹存在
            if (!Directory.Exists(LogDirectory))
            {
                Directory.CreateDirectory(LogDirectory);
            }
        }

        /// <summary>
        /// 写入信息日志
        /// </summary>
        /// <param name="message">日志内容</param>
        public static void Info(string message)
        {
            WriteLog("INFO", message);
        }

        /// <summary>
        /// 写入错误日志
        /// </summary>
        /// <param name="message">日志内容</param>
        /// <param name="exception">异常信息（可选）</param>
        public static void Error(string message, Exception exception = null)
        {
            WriteLog("ERROR", $"{message}{Environment.NewLine}{exception}");
        }

        /// <summary>
        /// 写入调试日志
        /// </summary>
        /// <param name="message">日志内容</param>
        public static void Debug(string message)
        {
            WriteLog("DEBUG", message);
        }

        /// <summary>
        /// 写入日志文件
        /// </summary>
        /// <param name="level">日志级别</param>
        /// <param name="message">日志内容</param>
        private static void WriteLog(string level, string message)
        {
            try
            {
                // 每天一个日志文件，按日期命名
                string logFilePath = Path.Combine(LogDirectory, $"{DateTime.Now:yyyy-MM-dd}.log");
                string logMessage = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff} [{level}] {message}";

                // 将日志写入文件
                lock (typeof(LogHelper)) // 确保多线程安全
                {
                    File.AppendAllText(logFilePath, logMessage + Environment.NewLine);
                }
            }
            catch
            {
                // 防止日志写入失败引发异常
                // 可根据需要处理异常
            }
        }
    }
}
